package com.dindang.ddm.mvp.presenter;

import android.app.Application;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.dindang.ddm.app.AppConst;
import com.dindang.ddm.app.utils.Base64Util;
import com.dindang.ddm.mvp.contract.LoginContract;
import com.dindang.ddm.mvp.model.entity.BaseResponse;
import com.dindang.ddm.mvp.ui.activity.MainActivity;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.model.LoginEvent;
import com.longxi.gamer_base.model.MessageEvent;
import com.longxi.gamer_base.model.User;
import com.longxi.gamer_base.utils.SharedPreferencesUtils;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/23/2019 19:22
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private User.UserLoginParam mParam = new User.UserLoginParam();
    private LoginEvent mLoginEvent = new LoginEvent();
    private WaitDialog mWaitDialog;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mParam = null;
        this.mLoginEvent = null;
    }

    public void initView() {
    }

    public void initListener() {
        mRootView.getBtnLogin().setOnClickListener(v -> {
            mWaitDialog = new WaitDialog(mRootView.getActivity());
            String name = mRootView.getEtName().getText().toString().trim();
            String password = mRootView.getEtPassword().getText().toString().trim();
            login(name, password);
        });
    }

    /**
     * 登录
     * @param name
     * @param password
     */
    private void login(String name, String password) {
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, com.dindang.checkline.R.string.data_load));
        if(TextUtils.isEmpty(name)){
            ArmsUtils.makeText(mApplication, mRootView.getEtName().getHint().toString().toString());
            return;
        }
        if(TextUtils.isEmpty(password)){
            ArmsUtils.makeText(mApplication, mRootView.getEtPassword().getHint().toString().toString());
            return;
        }

        mParam.account = name;
        mParam.password = Base64Util.encode(password.getBytes());
         //获取手机deviceId
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        String deviceId = pushService.getDeviceId();
        LogUtils.debugInfo("zp","设备序列号："+deviceId);
        mParam.cMacId = deviceId;
        mModel.login(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(0, 0))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {
            mWaitDialog.hideWaitingDialog();
        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<User.AccountInfo>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<User.AccountInfo> response) {
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }
                BaseAppConst.accountInfo = response.getData();
                String json = JSON.toJSONString(response.getData());
                SharedPreferencesUtils.setParam(mApplication, AppConst.KEY_ACCOUNT_INFO, json);
                if(mAppManager.activityClassIsLive(MainActivity.class)){
                    EventBus.getDefault().post(mLoginEvent);
                }else {
                    ARouter.getInstance().build("/activity/MainActivity").navigation(mAppManager.getCurrentActivity());
                }
                mRootView.getActivity().finish();
            }
        });
    }
}
